import register from '@/api/register'
import login from "../../api/login";

export default {
  // 获取所有省市区街道的树结构
  getAreaList(context) {
    return new Promise((resolve, reject) => {
      let areaList = context.state.areaList;
      if(areaList.length > 0) {
        resolve(areaList);
      } else {
        this.dispatch('request', register.getAreaList()).then(res => {
          context.commit('refreshAreaList', res.result);
          resolve(res.result);
        }).catch(e => {
          reject(e);
        })
      }
    })
  },
  /*
  * 异步获取所有省市区街道的数据
  * */
  getAreaListSync({state, commit}, params) {
    return new Promise((resolve, reject) => {
      if(params.code && state.areaListSync[params.code]) {
        resolve(state.areaListSync[params.code]);
        return;
      }
      if(!params.code && state.areaListSync.topList.length > 0) {
        resolve(state.areaListSync.topList);
        return;
      }

      this.dispatch('request', register.getAreaListByCode(params.code || '', params.level || '')).then(res => {
        let result = res.result;
        if(params.code) {
          commit('refreshSyncAreaListChild', {
            code: params.code,
            list: result
          });
        } else {
          commit('refreshSyncAreaList', result);
        }
        resolve(result);
      }).catch(e => {
        reject(e);
      })
    })
  },
  // 选择当前企业，并且获取对应的账号权限
  switchCurrent({commit}) {
    return new Promise((resolve, reject) => {
      this.dispatch('request', login.switchCurrent({tenantId: this.state.user.currentTenant.id})).then((res) => {
        commit('refreshUserRights', res.result);
        resolve(res);
      }).catch((e) => {
        reject(e)
      })
    })
  }
}
